/*  --- */
var BaseCrud;
(function(BaseCrud) {
	function fillValueWith(target, parameter) {
	    var keys = Object.keys(parameter);
	    for (var i in keys) {
	        var subParam = parameter[keys[i]];
	        if (typeof (subParam) === "object" && target[keys[i]] !== undefined) {
	            fillValueWith(target[keys[i]], subParam);
	        } else {
	            target[keys[i]] = subParam;
	        }
	    }
	}
	/**
	 * 
	 * @param {type} $scope
	 * @param {type} $routeParams
	 * @param {type} GenericResource
	 * @returns {undefined}
	 */
	function CrudCtrl($scope, $routeParams, GenericResource) {
	    $scope.searchCondition = {};
	    $scope.currentItem = {};
	    $scope.modelType = $routeParams.modelType;
	    $scope.search = function() {
	        $scope.itemsData = GenericResource.post({"modelType": $scope.modelType,"method":"search"}, $scope.searchCondition);
	        //$scope.totalServerItems = GenericResource.queryPost({"modelType": $scope.modelType,"method":"count"}, $scope.searchCondition);
	        //var htmlobj=$.ajax({url:root+'/rest/items/'+$scope.modelType+"/count", async:false,type: 'POST',dataType:'json'});
	        //$scope.totalServerItems =JSON.parse(htmlobj.responseText);   
	    };
	    $scope.add = function() {
	        $('#modelEdit').modal('show');
	    };
	    $scope.edit = function() {
	        if ($scope.mySelections.length !== 1) {
	            alert("请只选择一条数据进行编辑！");
	        } else {
	            $scope.currentItem = $scope.mySelections[0];
	            $('#modelEdit').modal('show');
	        }
	    };
	    $scope.remove = function() {
	        var delRow = $scope.mySelections[0];
	        var confirmDelete = confirm('您确定要删除数据？');
	        if (confirmDelete) {
	            var successCallback = function() {
	                $scope.displayError = false;
	                //$.messager.show({title: '提示', msg: '删除成功', timeout: 3000, showType: 'slide'});
	                //$('#listTable').datagrid('reload');
	            };
	            var errorCallback = function(result) {
	                $scope.displayError = true;
	                //$.messager.alert('提示', '删除失败!');
	            };
	            GenericResource.remove({"modelType": $scope.modelType,"method":"remove","id": delRow.id}, {}, successCallback, errorCallback);
	        }
	    };
	    $scope.save = function() {
	        var successCallback = function() {
	            $scope.displayError = false;
	            //alert("OK");
	            $scope.returnListView();
	            $scope.search();
	        };
	        var errorCallback = function(result) {
	            $scope.displayError = true;
	            $scope.errors = result.data[0];
	            $scope.errorKeys = Object.keys($scope.errors);
	        };
	        GenericResource.save({"modelType": $scope.modelType,"method":"update"}, $scope.currentItem, successCallback, errorCallback);
	    };
	    // 子元素操作
	    $scope.addChildrenItem = function(childrenItem) {
	        if (childrenItem === undefined) {            
	            return;
	        }
	        childrenItem.push({material: {price:1}});
	    };
	    $scope.clickRadio=function(index){
	        $scope.childrenIndex=index;
	    };
	    $scope.removeChildrenItem = function(childrenItem,index) {
	        if (childrenItem === undefined) {            
	            return;
	        }
	        childrenItem.splice(index,1);  
	    };
	    
	    $scope.returnListView = function() {
	        $scope.currentItem = {};
	        $('#modelEdit').modal('hide');
	    };
	    $scope.i18n = GenericResource.query({"path": "i18n","modelType": "all","method":"datas"});
	    var htmlobj = $.ajax({url: root + '/crudRest/i18n/forModel/' + $scope.modelType + '/TABLE', async: false});
	    $scope.columnDefs = JSON.parse(htmlobj.responseText);
	    $scope.mySelections = [];
	    $scope.searchCondition.pagingOptions = {
	        //pageSizes: [5, 15, 20],
	        pageSize: 15,
	        currentPage: 1
	    };
	    $scope.search();
	    $scope.$watch('searchCondition.pagingOptions', function(newVal, oldVal) {
	        if (newVal !== oldVal && (newVal.currentPage !== oldVal.currentPage || newVal.pageSize !== oldVal.pageSize)) {
	            $scope.search();
	        }
	    }, true);
	    $scope.gridOptions = {
	        data: 'itemsData',
	        selectedItems: $scope.mySelections,
	        multiSelect: false,
	        columnDefs: $scope.columnDefs.length === 0 ? undefined : 'columnDefs',
	        enablePaging: true,
	        showFooter: true,
	        totalServerItems: 'totalServerItems',
	        pagingOptions: $scope.searchCondition.pagingOptions,
	        i18n: 'zh-cn'
	    };
	    //$scope.settings = GenericResource.query({"path": "profile"});
	    var htmlobj = $.ajax({url: root + '/crudRest/profile/forModel/'+$scope.modelType, async: false});
	    $scope.settings = JSON.parse(htmlobj.responseText);
	    $scope.mergeSetting = function() {
	        var keys = Object.keys($scope.settings);
	        for (var i in keys)
	        {
	            var scopeVar = $scope[keys[i]];
	            if (scopeVar !== undefined) {
	                fillValueWith(scopeVar, $scope.settings[keys[i]]);
	                //angular.copy($scope.settings[keys[i]],scopeVar);
	                //angular.extend(scopeVar, $scope.settings[keys[i]]);
	            }
	        }
	    };
	    $scope.mergeSetting();
	}
	/**
	 * A group of combo box for select organization
	 */
	angular.module('organization', [])
	        .directive('myOrganization', function() {
	            return {
	            	//restrict: 'E',
	            	//replace: true,
	                transclude: false,
	                scope: {
	                    options: '@options',
	                    type: '@myOrganization',
	                    subValue: '=ngModel'
	                },
	                templateUrl: 'cascadeSelect.html',
	                controller: function($scope, $element, $attrs, $transclude, GenericResource) { 
	                    $scope.parentData = GenericResource.post({"modelType": "Group","method":"search"});
	                    $scope.$watch('level1Value', function(newValue) {
	                        if (newValue === null) {
	                            $scope.listInLevel1 = [];
	                            $scope.listInLevel2 = [];
	                            $scope.level2Value = undefined;
	                            $scope.employeeValue = undefined;
	                            $scope.positionValue = undefined;
	                        } else if (newValue !== undefined) {
	                            $scope.listInLevel1 = GenericResource.post({"modelType": "Group","method":"search"}, {example:{parent:{id: $scope.level1Value}}});
	                        }
	                    });
	                    $scope.$watch('level2Value', function(newValue) {
	                        if (newValue === null) {
	                            $scope.listInLevel2 = [];
	                            $scope.employeeValue = undefined;
	                            $scope.positionValue = undefined;
	                        } else if (newValue !== undefined) {
	                            $scope.listInLevel2 = GenericResource.post({"modelType": $scope.type,"method":"search"}, {example:{department:{id: $scope.level2Value}}});
	                        }
	                    });
	                    $scope.$watch('employeeValue', function(newValue) {
	                        if (newValue === null) {
	                        } else if (newValue !== undefined) {
	                            $scope.subValue = newValue;
	                        }
	                    });
	                    $scope.$watch('positionValue', function(newValue) {
	                        if (newValue === null) {
	                        } else if (newValue !== undefined) {
	                            $scope.subValue = newValue;
	                        }
	                    });
	                    $scope.$watch('subValue', function(newValue) {
	                         if(newValue !== undefined && newValue !==null){
	                           var successDept=function(result){
	                               $scope.level1Value = result[0].parent.id;                               
	                           };   
	                           var success=function(result){
	                               $scope.level2Value = result[0].department.id;
	                               $scope.listInLevel1 = GenericResource.post({"modelType": "Group","method":"search"}, {example:{id: result[0].department.id}},successDept);  
	                           };                                   
	                           if("Position" === $scope.type){
	                               $scope.positionValue=newValue;
	                           }else if("Employee" === $scope.type){
	                               $scope.employeeValue=newValue;
	                           }
	                           $scope.listInLevel2 = GenericResource.post({"modelType": $scope.type,"method":"search"}, {example:{id: newValue}},success);
	                         }
	                    });
	                }
	            };
	        });
	angular.module('dictionary', [])
	        .directive('myDictionary', function() {
	            return {
	                transclude: true,
	                scope: {
	                    type: '=myDictionary',
	                    subValue: '=ngModel',
	                    options: '@options'
	                },
	                template: function($scope) {
	                    var t = $scope.options;
	                    return '<select  ng-model="dictionaryValue" ng-options="t.key as t.value for t in dictItems" style="width: 120px">\n\
	                             <option value="">-请选择-</option>\n\
	                           </select> ';
	                },
	                controller: function($scope, GenericResource) {
	                    $scope.dictItems = GenericResource.post({"modelType": "Dictionary","method":"search"}, {"id": $scope.level1Value});
	                    $scope.$watch('dictionaryValue', function(newValue) {
	                        if (newValue === null) {
	                        } else if (newValue !== undefined) {
	                            $scope.subValue = newValue;
	                        }
	                    });
	                }
	            };
	        });
	angular.module('toOne', [])
	        .directive('toOne', function() {
	            return {
	                transclude: true,
	                scope: {
	                    modelType: '@toOne',
	                    subValue: '=ngModel',
	                    optionsText: '@options'
	                },
	                //template: '<select  ng-model="subValue" ng-options="t.id as t.type for t in dictItems" style="width: 100%">\n\
	                //             <option value="">-请选择-</option>\n\
	                //           </select> ',
	                template: function($scope) {
	                    //var options = $scope.context.dataset.options;
	                    return '<select  ng-model="subValue" style="width: 100%">\n\
	                             <option ng-selected="subValue === undefined || subValue === null || subValue ===\'\'" value="">-请选择-</option>\n\\n\
	                             <option ng-repeat="t in dictItems" ng-selected="subValue === t[options.id]" value="{{t[options.id]}}">{{$index}}&nbsp;&nbsp;{{t[options.name]}}</option>\n\
	                           </select>';
	                },
	                controller: function($scope, GenericResource) {
	                    $scope.options = $scope.optionsText === undefined ? {"id": "id", "name": "name"} : JSON.parse($scope.optionsText);
	                    $scope.dictItems = GenericResource.post({"modelType": $scope.modelType,"method":"search"}, {"id": $scope.level1Value});
	                    $scope.$watch('subValue', function(newValue) {
	                        if (newValue === null) {
	                        } else if (newValue !== undefined) {
	                            $scope.subValue = newValue;
	                        }
	                    });
	                }
	            };
	        });
	angular.module('d3force', [])
	        .directive('d3force', function() {
	            return {
	                transclude: true,
	                scope: {
	                    modelType: '@d3force',
	                    subValue: '=ngModel',
	                    optionsText: '@options'
	                },
	                link: function($scope, element, attrs) {
	                    var width = $scope.options.width;
	                    var height = $scope.options.height;
	                    var color = d3.scale.category20();
	                    var force = d3.layout.force()
	                            .charge(-120)
	                            .linkDistance(60)
	                            .size([width, height]);
	                    var svg = d3.select(element[0]).append("svg")
	                            .attr("width", width)
	                            .attr("height", height);
	
	                    d3.json("miserables.json", function(error, graph) {
	                        force
	                                .nodes(graph.nodes)
	                                .links(graph.links)
	                                .start();
	
	                        var link = svg.selectAll(".link")
	                                .data(graph.links)
	                                .enter().append("line")
	                                .attr("class", "link")
	                                .style("stroke-width", function(d) {
	                                    return Math.sqrt(d.value);
	                                });
	
	                        var node = svg.selectAll(".node")
	                                .data(graph.nodes)
	                                .enter().append("circle")
	                                .attr("class", "node")
	                                .attr("r", 5)
	                                .style("fill", function(d) {
	                                    return color(d.group);
	                                })
	                                .call(force.drag);
	
	                        node.append("title")
	                                .text(function(d) {
	                                    return d.name;
	                                });
	//                         node.append("text")
	//                                .text(function(d) {
	//                                    return d.name;
	//                                });
	
	                        force.on("tick", function() {
	                            link.attr("x1", function(d) {
	                                return d.source.x;
	                            })
	                                    .attr("y1", function(d) {
	                                        return d.source.y;
	                                    })
	                                    .attr("x2", function(d) {
	                                        return d.target.x;
	                                    })
	                                    .attr("y2", function(d) {
	                                        return d.target.y;
	                                    });
	
	                            node.attr("cx", function(d) {
	                                return d.x;
	                            })
	                                    .attr("cy", function(d) {
	                                        return d.y;
	                                    });
	                        });
	                    });
	                },
	                controller: function($scope, GenericResource) {
	                    $scope.options = $scope.optionsText === undefined ? {"width": 960, "height": 500} : JSON.parse($scope.optionsText);
	                }
	            };
	        });
	BaseCrud.CrudCtrl=CrudCtrl;
	angular.module('baseCrud', ['ngRoute','ngResource','ngGrid', '$strap.directives','organization','dictionary','toOne','d3force']).
	        config(['$routeProvider',
                     function($routeProvider) {
                         $routeProvider.
	                         when('/models/:modelType', {templateUrl: function(para) {
	                             return  'partials/' + para.modelType + '.html';
	                         }, controller: BaseCrud.CrudCtrl}).
	                         when('/modelsWithAutoPage/:modelType', {templateUrl: function(para) {
	                             return  '../../jaxrs/pageGenerator/' + para.modelType + '/html';
	                         }, controller: BaseCrud.CrudCtrl});
                     }]);
	angular.module('baseCrud').factory('GenericResource', function($resource) {
	    var resource = $resource(root+'/crudRest/:path/:modelType/:method/:id', {modelType: '@modelType', path: "items", method: null,id:null},
	    {
	        'queryAll': {method: 'GET', isArray: true},
	        'query': {method: 'GET', isArray: false},
	        'queryPost': {method: 'POST', isArray: false},
	        'update': {method: 'PUT'},
	        'save': {method: 'PUT'},
	        'post': {method: 'POST', isArray: true},
	        'remove': {
	            method: 'DELETE',
	            isArray: false,
	            headers: {'Content-Type': 'application/json'}
	        }
	    });
	    return resource;
	});
	angular.module('baseCrud').value('$strapConfig', {
	    datepicker: {
	        language: 'zh-CN',
	        format: 'yyyy-mm-dd'
	                //endDate: '2013-09-22'
	    }
	});
	//hawtioPluginLoader.addModule("baseCrud");
})(BaseCrud || (BaseCrud = {}));